#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

// 线程状态
static int number = 1;
enum class TSTATUS
{
    NEW,
    START,
    STOP
};

namespace ThreadMode
{
    using func_t = std::function<void()>;

    class mythread
    {

    private:
        static void *Routine(void *arg)
        {
            mythread *t = static_cast<mythread *>(arg);
            t->_status = TSTATUS::START;
            t->_func();
        }
        void EnableDetach()
        {
            _joinable = false;
        }

    private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 判断是否分离,默认不是
        func_t _func;
        TSTATUS _status;

    public:
        mythread(func_t func) : _func(func), _status(TSTATUS::NEW), _joinable(true)
        {
            _name = "Thread-" + std::to_string(number++);
            _pid = getpid();
        }
        bool strat()
        {
            if (_status != TSTATUS::START)
            {
                int n = ::pthread_create(&_tid, nullptr, Routine, this);
                if (n != 0)
                    return false;
                _status = TSTATUS::START;
                return true;
            }
            return false;
        }
        // 线程停止
        bool Stop()
        {
            if (_status == TSTATUS::START)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        // 线程
        bool join()
        {
            if (_joinable)
            {
                int n = pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }

        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }
        std::string Name()
        {
            return _name;
        }

        bool ISbleJoinble()
        {
            return _joinable;
        }
        ~mythread()
        {
        }
    };

}